//
//  Untitled.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/17.
//

import UIKit
open class TopLeftLabel: UILabel {
    
    // 设置内间距
    var textInsets: UIEdgeInsets = .zero {
        didSet {
            setNeedsDisplay()
        }
    }
    
    open override func drawText(in rect: CGRect) {
        // 根据内间距调整绘制区域
        let insetRect = rect.inset(by: textInsets)
        
        // 获取文本实际大小
        guard let text = text else { return }
        let textSize = (text as NSString).boundingRect(
            with: CGSize(width: insetRect.width, height: .greatestFiniteMagnitude),
            options: [.usesLineFragmentOrigin, .usesFontLeading],
            attributes: [.font: font ?? UIFont.systemFont(ofSize: 17)],
            context: nil
        ).size
        
        // 重新定义绘制区域，使文本始终靠左上角
        var adjustedRect = insetRect
        adjustedRect.size.height = min(textSize.height, insetRect.height)
        
        // 调用父类的绘制方法
        super.drawText(in: adjustedRect)
    }
    
    open override var intrinsicContentSize: CGSize {
        // 根据内容大小和内间距调整固有内容大小
        guard let text = text else { return .zero }
        let textSize = (text as NSString).boundingRect(
            with: CGSize(width: bounds.width - textInsets.left - textInsets.right, height: .greatestFiniteMagnitude),
            options: [.usesLineFragmentOrigin, .usesFontLeading],
            attributes: [.font: font ?? UIFont.systemFont(ofSize: 17)],
            context: nil
        ).size
        let width = textSize.width + textInsets.left + textInsets.right
        let height = textSize.height + textInsets.top + textInsets.bottom
        return CGSize(width: width, height: height)
    }
    
    open override func sizeThatFits(_ size: CGSize) -> CGSize {
        // 调整 `sizeThatFits` 的结果以包含内间距
        guard let text = text else { return .zero }
        let textSize = (text as NSString).boundingRect(
            with: CGSize(width: size.width - textInsets.left - textInsets.right, height: .greatestFiniteMagnitude),
            options: [.usesLineFragmentOrigin, .usesFontLeading],
            attributes: [.font: font ?? UIFont.systemFont(ofSize: 17)],
            context: nil
        ).size
        let width = textSize.width + textInsets.left + textInsets.right
        let height = textSize.height + textInsets.top + textInsets.bottom
        return CGSize(width: width, height: height)
    }
}
